package com.jeesite.modules.conf;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class AppController implements Serializable {
    private static final Logger logger=LoggerFactory.getLogger(AppController.class);
    private static final String DateTimeFormat="yyyy-MM-dd HH:mm:ss";
    private static final String DateFormat="yyyy-MM-dd";
    private static final String TimeFormat="HH:mm:ss";
    /**
     * 应答JSON
     */
    public static void renderString(HttpServletResponse response,JSONObject json){
    	String str=JSONObject.toJSONStringWithDateFormat(json, DateTimeFormat, SerializerFeature.WriteDateUseDateFormat);
    	renderString(response, str,"application/json;charset=UTF-8");
    }
    /**
     * 客户端返回字符串
     */
    public static void renderString(HttpServletResponse response,String string,String type) {
    	try {
			response.reset();
			response.setContentType(type);
			response.setCharacterEncoding("UTF-8");
			response.getWriter().print(string);
		} catch (Exception e) {
			logger.warn("下发数据【{}】失败",string);
		}
    }
    /**
     * 返回错误信息
     */
    public static void renderErrorString(HttpServletResponse response,Pair pair,String errorMessage) {
    	JSONObject result=new JSONObject();
    	result.put("code", pair.getKey());
    	result.put("message", pair.getValue()+errorMessage);
    	String str=JSONObject.toJSONStringWithDateFormat(result, DateTimeFormat, SerializerFeature.WriteDateUseDateFormat);
    	renderString(response, str, "application/json;charset=UTF-8");
    }
    /**
     * 显示错误信息
     */
    public static void renderShowErrorString(HttpServletResponse response,Pair pair) {
    	renderErrorString(response, pair, "");
    }
    /**
     * 成功返回数据信息
     */
    public static void renderSuccessObject(HttpServletResponse response,Object obj,Pair pair) {
    	JSONObject result=new JSONObject();
        result.put("code", pair.getKey());
        result.put("message", pair.getValue());
        if(obj!=null){
        	result.put("data", obj);
        }
        String str=JSONObject.toJSONStringWithDateFormat(result, DateTimeFormat, SerializerFeature.WriteDateUseDateFormat);
        renderString(response,str,"application/json;charset=UTF-8");
    }
}
